//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels
{
    using System;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.Controllers;

    public class ChatPageViewModel : ViewModel
    {
        private readonly ChatTopicViewModel topicViewModel;
        private readonly ChatMessageViewModel currentMessage;
        private readonly ChatMessageReceiver receiver;

        public ChatPageViewModel(ChatTopicViewModel topicViewModel)
        {
            if (topicViewModel == null)
            {
                throw new ArgumentNullException("topicViewModel");
            }

            this.topicViewModel = topicViewModel;
            this.currentMessage = new ChatMessageViewModel(App.Context.UserName, string.Empty);

            this.receiver = new ChatMessageReceiver(this.topicViewModel);
        }

        public event MessageReceivedEventHandler MessageReceived
        {
            add { this.receiver.MessageReceived += value; }
            remove { this.receiver.MessageReceived -= value; }
        }

        public string TopicName
        {
            get { return this.TopicViewModel.Name; }
        }

        public ChatTopicViewModel TopicViewModel
        {
            get { return this.topicViewModel; }
        }

        public ChatMessageViewModel CurrentMessage
        {
            get { return this.currentMessage; }
        }

        public ChatMessageReceiver Receiver
        {
            get { return this.receiver; }
        }

        internal void OnPageOpened()
        {
            this.receiver.IsEnabled = true;
        }

        internal void OnSendMessage()
        {
            if (Commands.SendMessage.CanExecute(this))
            {
                Commands.SendMessage.Execute(this);
            }
        }

        internal void OnPageClosed()
        {
            this.receiver.IsEnabled = false;
        }
    }
}
